package cn.sunshine.ymcc.security;

import cn.sunshine.ymcc.domain.Login;
import cn.sunshine.ymcc.domain.Permission;
import cn.sunshine.ymcc.mapper.PermissionMapper;
import cn.sunshine.ymcc.service.ILoginService;
import cn.sunshine.ymcc.service.IPermissionService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
/*
 * @Title:
 * @Description: Security基于数据库的登录
 * @Author: Mr.Jiang
 * @Version: 1.0
 * @Date:  2022/8/26 21:52
 * @Parameters:
 * @Return
 */
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private ILoginService loginService;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 1.去数据库区查询登录人信息
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username);
        Login login = loginService.selectOne(wrapper);
        if (login != null) {
            // 2.再查询权限信息
            List<Permission> permissions = permissionMapper.LoadselectByLoginId(login.getId());
            List<SimpleGrantedAuthority> authorities = permissions.stream()
                    .map(permission -> {return new SimpleGrantedAuthority(permission.getSn());})
                    .collect(Collectors.toList());
            return new User(
                    login.getUsername(),
                    login.getPassword(),
                    login.getEnabled(),
                    login.getAccountNonExpired(),
                    login.getCredentialsNonExpired(),
                    login.getAccountNonLocked(),
                    authorities);


        }
        return null;
    }
}
